package com.hui.qiniucloud.mapper;

import com.hui.qiniucloud.entity.ChatMessage;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Delete;

import java.util.List;
import java.util.Map;

/**
 * 聊天消息 Mapper 接口
 */
@Mapper
public interface ChatMessageMapper extends BaseMapper<ChatMessage> {

    /**
     * 根据会话ID查询消息列表
     */
    @Select("SELECT * FROM chat_message WHERE session_id = #{sessionId} AND deleted = 0 ORDER BY created_time ASC")
    List<ChatMessage> selectBySessionId(@Param("sessionId") Long sessionId);

    /**
     * 根据会话ID查询消息列表（用于API调用的格式）
     */
    @Select("SELECT role, content FROM chat_message WHERE session_id = #{sessionId} AND deleted = 0 ORDER BY created_time ASC")
    List<Map<String, String>> selectApiFormatBySessionId(@Param("sessionId") Long sessionId);

    /**
     * 根据会话ID查询消息数量
     */
    @Select("SELECT COUNT(*) FROM chat_message WHERE session_id = #{sessionId} AND deleted = 0")
    Integer countBySessionId(@Param("sessionId") Long sessionId);

    /**
     * 根据会话ID查询最后一条用户或助手消息
     */
    @Select("SELECT content FROM chat_message WHERE session_id = #{sessionId} AND deleted = 0 AND role IN ('user', 'assistant') ORDER BY created_time DESC LIMIT 1")
    String selectLastContentBySessionId(@Param("sessionId") Long sessionId);

    /**
     * 物理删除会话的所有消息
     */
    @Delete("DELETE FROM chat_message WHERE session_id = #{sessionId}")
    int deleteBySessionId(@Param("sessionId") Long sessionId);

    /**
     * 根据会话ID列表批量查询最新的消息内容
     */
    @Select("<script>" +
            "SELECT DISTINCT " +
            "  m.session_id, " +
            "  m.content " +
            "FROM chat_message m " +
            "INNER JOIN ( " +
            "  SELECT session_id, MAX(created_time) as max_time " +
            "  FROM chat_message " +
            "  WHERE session_id IN " +
            "  <foreach collection='sessionIds' item='sessionId' open='(' close=')' separator=','>" +
            "    #{sessionId}" +
            "  </foreach>" +
            "  AND deleted = 0 AND role IN ('user', 'assistant') " +
            "  GROUP BY session_id " +
            ") latest ON m.session_id = latest.session_id AND m.created_time = latest.max_time " +
            "WHERE m.deleted = 0" +
            "</script>")
    List<Map<String, Object>> selectLastContentBySessionIds(@Param("sessionIds") List<Long> sessionIds);
}